<?php
// +----------------------------------------------------------------------
// | YotakuCMS
// +----------------------------------------------------------------------
// | Copyright (c) 2016 http://www.yotaku.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: Creatint <creatint@163.com> 
// +----------------------------------------------------------------------

namespace Home\Controller;

/**
 * 文档模型控制器
 * 文档模型列表和详情
 */
class DealerController extends HomeController {
    public function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
        // 获取dashboard数据
        $dashboard = D('UcenterMember')->where('id='.session('user_auth.uid'))->field("quota,quota2,used,used2")->find();
        $dashboard['pass'] = D('Record')->where(['user_id'=>session('user_auth.uid'),'status'=>['in',[1]]])->count('id');
         $dashboard['passed2'] = D('Record')->where(['user_id'=>session('user_auth.uid'),'type'=>1,'status'=>['in',[1]]])->count('id');
         $dashboard['passed3'] = D('Record')->where(['user_id'=>session('user_auth.uid'),'type'=>2,'status'=>['in',[1]]])->count('id');

         $dashboard['price'] = D('Record')->where(['user_id'=>session('user_auth.uid'),'status'=>['in',[1]]])->sum('price');
        $dashboard['price'] = round($dashboard['price'],2);
        $this->assign('dashboard',$dashboard);
    }

    /* 文档模型频道页 */
	public function index(){
		$this->assign('controller','Dealer');
		$this->assign('action','index');


		// 记录文档模型
        $Record = D('Record');

        //是否搜索
        $query = ['status'=>['in',[0,1,2]],'user_id'=>session('user_auth.uid')];
        // 获取查询条件
        $query = add_search($query, I('get.'));
        // 获取记录列表
		$list = $Record->lists($query, !empty($_GET['p'])?$_GET['p']:1, C('ROW'));

		//分页
		$this->assign('row',C('ROW'));
		$page = new \Common\Tool\Page($Record->listCount($query), C('ROW'));
		$page->setConfig('them','');
		$this->assign('_page',$page->show());
		$this->assign('list',$list);

		$this->display();
	}


    /**
     * 新增记录.
     * 错误代码：
     * E0201:无配额
     * E0202:传回价格不正确
     *
     */
	public function add(){
		$this->assign('controller',CONTROLLER_NAME);
		$this->assign('action','add');
//		dump($_POST);
//		dump(!empty($_POST['platenumber_1']) && !empty($_POST['type']) && !empty($_POST['platenumber_2']) && !empty($_POST['car']) && !empty($_POST['tyre']) && !empty($_POST['price']) && !empty($_POST['images']) && !empty($_POST['number']));
//		exit;

		if( !empty($_POST['platenumber_1']) && !empty($_POST['type']) && !empty($_POST['platenumber_2']) && !empty($_POST['car']) && !empty($_POST['tyre']) && !empty($_POST['price']) && !empty($_POST['images']) && !empty($_POST['number'])){

		    // TODO:检查配额

            // 数据预处理
             // 检查活动形式
             if ($_POST['type'] == 1){
                  $_POST['number'] = 1;

                  $price = 1000;
             } else {
                  $price = 350;
             }
             if($_POST['type'] == 2){


             }

            // 数量检查
            if (!($_POST['number'] == 1 || $_POST['number'] == 2)) {
                $this->error('请检查是否选择了轮胎数量',U('Dealer/add'));
            }

            // 是否有轮胎ID
            if ( !($tyre = M("Tyre")->find($_POST['tyre'])) ){
                $this->error('请检查是否选择了轮胎型号',U('Dealer/add'));
                trace('请检查是否选择了轮胎型号');
                exit;
            }

            // 价格是否正确
            if ( $_POST['price'] != $price * $_POST['number'] ) {
                $this->error('E0202',U('Dealer/add'));
            }
            //检查形式二剩余配额
//             if（$_POST[number] < {$dashboard['quota']-$dashboard['used']+$dashboard['used2']-$dashboard['quota2']}）{}


            // 填充记录数据
            $data = [];

            // 当前用户id
            $data['user_id'] = session("user_auth.uid");

            // 车牌号
			$data['plate_number'] = strtoupper($_POST['platenumber_1'].$_POST['platenumber_2']);

			// 任务委托书ids
            $data['images'] = $_POST['images'];

            // 其他数据
             $data['type'] = $_POST['type'];
            $data['dealer_name'] = session('user_auth.username');  //  轮胎记录id
            $data['tyre_id'] = $_POST['tyre'];  //  轮胎记录id
            $data['car'] = $_POST['car'];   // 车型
            $data['price'] = $price * $_POST['number']; // 价格
            $data['number'] = $_POST['number']; // 数量
            $data['tyre_brand'] = $tyre['brand']; // 轮胎品牌
            $data['tyre_type'] = $tyre['type'];     // 轮胎型号
            $data['tyre_number'] = $tyre['number']; // 轮胎备件号

            // 记录模型
			$Record   =   D('Record');

			// 检查车牌号是否重复，需排除已删除记录
            $map = [
                'plate_number'=>$data['plate_number'],
                'status'=>['neq',3]
            ];
            if ( $res = $Record->where($map)->select() ){
                $this->error('车牌号已存在',U('Dealer/add'));
                exit;
            }

            // 检查是否有剩余配额
            if ( session('user_auth.uid') > 0 ){
                $user = D('UcenterMember')->find(session('user_auth.uid'));
                // 形式一配额检查
                 if ( $_POST['type'] == 1 &&  !($user['quota2'] - $user['used2'] >= $_POST['number']) ) {
                      $this->error('您的形式1配额已不足',U('Dealer/add'));

                 }
                 if ( $_POST['type'] == 2 &&  !($user['quota']-$user['used']+$user['used2']-$user['quota2'] >= $_POST['number']) ) {
                      $this->error('您的形式2配额已不足',U('Dealer/add'));
                      exit;
                 }
                 //形式二配额检查
//                 if($_POST['type'] == 2 && !)
                // 配额检查
                if ( !($user['quota'] - $user['used'] >= $_POST['number']) ) {
                    $this->error('您的总配额已不足',U('Dealer/add'));
                     exit;

                }

            } else {
                $this->error('账号未登录',U('User/logout'));
                exit;
            }


			if ( $Record->create($data) && $res = $Record->add() ){
                // 增加记录成功，减少总配额
                D('UcenterMember')->where('id='.session('user_auth.uid'))->setInc('used',$_POST['number']);
                 // 增加记录成功，减少形式一配额
                if ( $_POST['type'] == 1 ) {
                     D('UcenterMember')->where('id='.session('user_auth.uid'))->setInc('used2',$_POST['number']);
                }



			    $this->success('增加记录成功',U('Dealer/index'));
            }

            else {
			    $this->error('增加记录失败 '.$Record->getError(),U('Dealer/add'));
            }
		}else{
		    // 表单恢复
            $this->assign('info',$_POST);
            // 获取车型数据
            $cars = D("Tyre")->group('car')->select();
            $this->assign('cars',$cars);

			$this->display();
		}
	}

     /**
      * 新增记录.
      * 错误代码：
      * E0201:无配额
      * E0202:传回价格不正确
      *
      */
     public function edit($id = null){
          $this->assign('controller',CONTROLLER_NAME);
          $this->assign('action','add');
//		dump($_POST);
//		dump(!empty($_POST['platenumber_1']) && !empty($_POST['type']) && !empty($_POST['platenumber_2']) && !empty($_POST['car']) && !empty($_POST['tyre']) && !empty($_POST['price']) && !empty($_POST['images']) && !empty($_POST['number']));
//		exit;

          if(!empty($_POST['id']) && !empty($_POST['platenumber_1']) && !empty($_POST['type']) && !empty($_POST['platenumber_2']) && !empty($_POST['car']) && !empty($_POST['tyre']) && !empty($_POST['price']) && !empty($_POST['images']) && !empty($_POST['number'])){

               $xingshi = 0;// 记录的形式，1或2
               $fangshi = 0;// 库存改变方式，-1还原1,0不变，1用掉1

               // 检查用户与配额、形式
               if ( session('user_auth.uid') > 0 ){
                    // 验证账号
                    if ( !($user = D('UcenterMember')->find(session('user_auth.uid')))) {
                         $this->error('账号未登录',U('User/logout'));
                         exit;
                    }
                    // 获取原数据 验证是否可编辑
                    if (!($old = D('Record')->where(['id'=>$_POST['id'], 'status'=>['in',[2]],'user_id'=>$user['id'],'_logic'=>'and'])->find())) {
                         $this->error('无可编辑记录',U('Dealer/index'));
                         exit;
                    }
                    // 检查活动形式
                    $_POST['type'] = $old['type'];
                    if ($_POST['type'] == 1){
                         $_POST['number'] = 1;
                         $price = 1000;
                    } else {
                         $price = 350;
                    }
                    // 判断形式
                    if ((int)$old['type'] === 1) {
                         $xingshi = 1;
                    } elseif((int)$old['type'] === 2) {
                         $xingshi = 2;
                         if ($old['number'] > $_POST['number']) {
                              // 库存还原1
                              $fangshi = -1;
                         } elseif ($old['number'] < $_POST['number']) {
                              // 库存扣1
                              $fangshi = 1;
                              // 形式二用掉库存需要检查余额
                              if ( $_POST['type'] == 2 &&  !($user['quota']-$user['used']+$user['used2']-$user['quota2'] >= 1) ) {
                                   $this->error('您的形式2配额已不足',U('Dealer/edit'));
                                   exit;
                              }
                         }
                    } else {
                         $this->error('无可编辑记录',U('Dealer/index'));
                         exit;
                    }
               } else {
                    $this->error('账号未登录',U('User/logout'));
                    exit;
               }


               // 数量检查
               if (!($_POST['number'] == 1 || $_POST['number'] == 2)) {
                    $this->error('请检查是否选择了轮胎数量',U('Dealer/edit'));
               }

               // 是否有轮胎ID
               if ( !($tyre = M("Tyre")->find($_POST['tyre'])) ){
                    $this->error('请检查是否选择了轮胎型号',U('Dealer/edit'));
                    trace('请检查是否选择了轮胎型号');
                    exit;
               }

               // 价格是否正确
               if ( $_POST['price'] != $price * $_POST['number'] ) {
                    $this->error('E0202',U('Dealer/add'));
               }

               // 填充记录数据
               $data = [];
               $data['id'] = $_POST['id'];
               $data['status'] = 0;

               // 当前用户id
               $data['user_id'] = session("user_auth.uid");

               // 车牌号
               $data['plate_number'] = strtoupper($_POST['platenumber_1'].$_POST['platenumber_2']);

               // 任务委托书ids
               $data['images'] = $_POST['images'];

               // 其他数据
               $data['type'] = $_POST['type'];
               $data['dealer_name'] = session('user_auth.username');  //  轮胎记录id
               $data['tyre_id'] = $_POST['tyre'];  //  轮胎记录id
               $data['car'] = $_POST['car'];   // 车型
               $data['price'] = $price * $_POST['number']; // 价格
               $data['number'] = $_POST['number']; // 数量
               $data['tyre_brand'] = $tyre['brand']; // 轮胎品牌
               $data['tyre_type'] = $tyre['type'];     // 轮胎型号
               $data['tyre_number'] = $tyre['number']; // 轮胎备件号

               // 记录模型
               $Record   =   D('Record');

               // 检查车牌号是否重复，需排除已删除记录
               $map = [
                   'plate_number'=>$data['plate_number'],
                   'status'=>['neq',3],
                    'id'=>['neq',$_POST['id']]
               ];
               if ( $res = $Record->where($map)->select() ){
                    $this->error('车牌号已存在',U('Dealer/edit'));
                    exit;
               }

               // 更新数据，并处理库存
               if ( ($data = $Record->create($data)) && ($res = $Record->save($data))){
                    if (1 === $xingshi) {
                         // 形式一不需要修改配额
                    } elseif (2 === $xingshi) {
                         if ($fangshi === -1) {// 还原1
                              D('UcenterMember')->where('id='.session('user_auth.uid'))->setDec('used',1);
                         } elseif ($fangshi === 1) {// 增加1
                              D('UcenterMember')->where('id='.session('user_auth.uid'))->setInc('used',1);
                         }
                    }
                    $this->success('修改记录成功',U('Dealer/index'));
               } else {
                    $this->error('修改记录失败 '.$Record->getError(),U('Dealer/edit'));
               }
          }else{
               // 获取车型数据
               $cars = D("Tyre")->group('car')->select();
               $this->assign('cars',$cars);

               // 获取记录数据
               $info = D("Record")->find($id);

               // 获取图片
               $images = D('Picture')->where(['id'=>['in',$info['images']]])->select();
               $info['images'] = $images;
//               dump($info);
               // 记录的数据
               $this->assign('info', $info);

               $this->display();
          }
     }

	public function upload(){
        $return = array('status'=>0,'info'=>'上传失败');
        if(!IS_POST){
            $this->ajaxReturn($return);
        }
//        dump($_FILES);

        /* 调用文件上传组件上传文件 */
        $Picture = D('Picture');
        $pic_driver = C('PICTURE_UPLOAD_DRIVER');
        $info = $Picture->upload(
            $_FILES,
            C('PICTURE_UPLOAD'),
            C('PICTURE_UPLOAD_DRIVER'),
            C("UPLOAD_{$pic_driver}_CONFIG")
        );

        /* 记录图片信息 */
        if($info){
            $return['status'] = 1;
            $return['info'] =   '上传成功';
            $return = array_merge($info['Filedata'], $return);
        } else {
            $return['status'] = 0;
            $return['info'] = $Picture->getError();
        }


        $this->ajaxReturn($return);
    }


    // api方法
    public function api(){
        $res = array();
        if ( $_POST['action'] == 'getTyres' && $_POST['car'] ) {

            if ( $tyre = D('Tyre')->where("car='{$_POST['car']}'")->select() ){
                $res['status'] = 1;
                $res['msg'] = '修改成功';
                $res['data'] = $tyre;
            } else {
                $res['status'] = 0;
                $res['msg'] = '修改失败 '. D('UcenterMember')->getError();
            }
        } elseif( $_POST['action'] == 'getQuota' && $_POST['uid']) {
            $res['status'] = 1;
            $res['msg'] = 'ddd';
            $res['data'] = D('UcenterMember')->where('id='.I('post.uid'))->field("quota,used")->find();
            $res['data']['price'] = D('Record')->where(['user_id'=>I('post.uid'),'status'=>['in',[1]]])->sum('price');
            $res['data']['price'] = round($res['data']['price'],2);
        }


        $this->ajaxReturn($res);

    }

}
